<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../static/css/minghu.css">
     <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>教练收入统计</title>
    <style>
        body {
            max-width: 96%;
            margin: 0 auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
        }
        .date-input {
            margin: 20px 0;
            padding: 8px;
        }
        .yes-mark {
            color: red;
            font-weight: bold;
        }
        .no-mark {
            color: #333;
        }
    </style>
</head>
<body>
     {% include 'show_ins_info.html' %}
    <h1>教练收入统计</h1>
    
    <div>
        <label for="month-input">选择月份: </label>
        <input type="month" id="month-input" class="date-input" onchange="filterByMonth()">
    </div>
        <div style="display: flex; align-items: center; gap: 10px;">
            <label for="ins-select">选择教练: </label>
            <select id="ins-select" class="date-input" onchange="filterByMonth()">
                <option value="">请选择教练</option>
            </select>
            <span id="ins-type-display" style="font-size: 14px; color: #666;"></span>
        </div>
        <div style="display: flex; align-items: center; gap: 10px; margin-top: 10px;">
            <label>基本合作咨询费: </label>
            <input type="text" id="basic-salary-input" style="padding: 5px; width: 100px;">
            <div>备注 
                <input type="text" id="basic-salary-comment" style="padding: 5px; width: 400px;">
            </div>
        </div>

    <div id="salary-title" style="display: none; margin-top: 20px;">
        <h2>私教课结算清单</h2>
    </div>

    <table id="salary-table">
        <thead>
            <tr>
                <th>会员卡号</th>
                <th>课程类型</th>
                <th>课程名称</th>
                <th>会员ID</th>
                <th>会员姓名</th>
                <th>教练ID</th>
                <th>教练姓名</th>
                <th>课时数</th>
                <th>开卡日期</th>
                <th>开卡天数</th>
                <th>应付金额</th>
                <th>实付金额</th>
                <th>单节课价格</th>
                <th>购课日期</th>
                <th>课提金额</th>
                <th>是否在本月结算</th>
                <th>备注</th>
            </tr>
        </thead>
        <tbody>
            <!-- 数据将通过JavaScript动态填充 -->
        </tbody>
    </table>
    <div id="commission-summary" style="display: none; margin-top: 20px;">
        <label>本月课提结算金额: </label>
        <input type="text" id="commission-total" style="padding: 5px; width: 100px;"> 元
    </div>

    <!-- 未结算私教课程清单 -->
    <div id="unsettled-title" style="display: none; margin-top: 30px;">
        <h2>未结算私教课程清单</h2>
    </div>

        <table id="unsettled-table" style="display: none; margin-top: 10px;">
        <thead>
            <tr>
                <th>序号</th>
                <th>卡号</th>
                <th>课程类型</th>
                <th>课程名称</th>
                <th>会员姓名</th>
                <th>购课日期</th>
                <th>开卡日期</th>
                <th>开卡天数</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <!-- 小团课结算清单 -->
    <div id="group-class-title" style="display: none; margin-top: 30px;">
        <h2>小团课结算清单</h2>
    </div>

    <table id="group-class-table" style="display: none; margin-top: 10px;">
        <thead>
            <tr>
                <th>序号</th>
                <th>团课成员</th>
                <th>课程性质</th>
                <th>课程名称</th>
                <th>上课时间</th>
                <th>上课节数</th>
                <th>结算课提</th>
                <th>是否在本月结算</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <div id="group-class-summary" style="display: none; margin-top: 20px;">
        <label>小团课课提结算金额: </label>
        <input type="text" id="group-class-commission-total" style="padding: 5px; width: 100px;" oninput="updateGroupClassCommissionFromInput()"> 元
    </div>

    <div id="sales-title" style="display: none; margin-top: 30px;">
        <h2>销售清单</h2>
    </div>

    <table id="sales-table" style="display: none; margin-top: 10px;">
        <thead>
            <tr>
                <th>序号</th>
                <th>客户姓名</th>
                <th>购课时间</th>
                <th>卡号</th>
                <th>教练</th>
                <th>应付金额</th>
                <th>实付金额</th>
                <th>备注</th>
                <th>是否在本月结算</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <div style="margin-right: 10px; padding: 5px 10px;">
        <button id="select-all-btn" style="margin-right: 10px; padding: 5px 10px;">全选</button>
        <button id="deselect-all-btn" style="margin-right: 10px; padding: 5px 10px;">全不选</button>
    </div>

    <div id="sales-summary" style="display: none; margin-top: 20px;">
        
        <label>本月销售金额: </label>
        <input type="text" id="sales-total" style="padding: 5px; width: 100px;" oninput="calculateSalesCommissionFromInput()">  元
    </div>
    <div id="sales-commission-summary" style="display: none; margin-top: 10px;">
        <label>本月销提金额: </label>
        <input type="text" id="sales-commission-total" readonly style="padding: 5px; width: 100px;"> 元
        <div id="commission-rates-info" style="margin-top: 5px; font-size: 12px; color: #666;">
            <span>销提区间: </span>
            <span id="current-rate-info"></span>
        </div>
    </div>

    <div style="margin-top: 20px;">
        <div style="margin-bottom: 15px;">
            <label>其他情况说明: </label>
            <textarea id="other-remarks" style="width: 100%; min-height: 60px; padding: 5px;"></textarea>
        </div>
        <div style="margin-bottom: 15px;">
            <label>其他情况涉及金额: </label>
            <input type="number" id="other-amount" step="0.01" value="0" style="padding: 5px; width: 100px;"> 元
        </div>
        <button id="confirm-btn" style="padding: 8px 16px;">生成核算报告</button>
    </div>

    <div id="result-container" style="margin-top: 30px; display: none;">
        <h2 id="report-title"></h2>

        <div id="basic-salary-section" style="margin-bottom: 15px;">
                <h3>· 基本合作费用: 
                <span id="basic-salary-display" style="font-weight: lighter;"></span></h3>
        </div>
        
        <div id="private-class-section">
            
            <h3>· 私教课合作课提结算表</h3>
            <table id="private-class-table">
                <thead>
                    <tr>
                        <th>会员卡号</th>
                        <th>课程类型</th>
                        <th>课程名称</th>
                        <th>会员姓名</th>
                        <th>开卡日期</th>
                        <th>开卡天数</th>
                        <th>课时数</th>
                        <th>购课日期</th>
                        <th>应收金额</th>
                        <th>实收金额</th>
                        <th>单节课价格</th>
                        <th>课提金额</th>
                        <th>备注</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <p>- 本月私教课合作课提结算金额: <strong><span id="private-class-total"></span></strong> 元</p>
        </div>

        <div id="group-class-section" style="display: none;">
            <h3>· 小团课合作课提结算表</h3>
            <table id="group-class-report-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>团课成员</th>
                        <th>课程性质</th>
                        <th>课程名称</th>
                        <th>上课时间</th>
                        <th>上课节数</th>
                        <th>结算课提</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <p>- 本月小团课合作课提结算金额: <strong><span id="group-class-report-total"></span></strong> 元</p>
        </div>

        <div id="unsettled-section" style="display: none; margin-top: 20px;">
            <h3>· 未结算私教课程清单</h3>
            <table id="unsettled-report-table">
                <thead>
                    <tr>
                        <th>卡号</th>
                        <th>课程类型</th>
                        <th>课程名称</th>
                        <th>会员姓名</th>
                        <th>购课日期</th>
                        <th>开卡日期</th>
                        <th>开卡天数</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>

        <div id="sales-section" style="display: none;">
            <h3>· 销售合作提成结算表</h3>
            <table id="sales-report-table">
                <thead>
                    <tr>
                        <th>客户姓名</th>
                        <th>购课时间</th>
                        <th>卡号</th>
                        <th>应付金额</th>
                        <th>实付金额</th>
                        <th>备注</th>
                        <th>销售提成</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <p>- 本月合作销售金额: <strong><span id="sales-report-total"></span></strong> 元</p>
            <p>- 本月合作销售提成金额: <strong><span id="sales-commission-report-total"></span></strong> 元</p>
            <p id="commission-rate-info"></p>
        </div>

        <hr style="margin: 20px 0; border: 1px solid #ddd;">

        <div id="total-section">
            <h3 id="total-cooperation-fee"></h3>
        </div>
        </div>
        
        <button id="save-report-btn" style="padding: 8px 16px; margin-left: 10px; display: none;">保存报告</button>
    </div>

    <script src="../static/js/common.js"></script>
    <script>
        // 保存报告功能
        document.getElementById('save-report-btn').addEventListener('click', function() {
            // 收集报告数据
            const reportData = {
                month: document.getElementById('month-input').value,
                insId: document.getElementById('ins-select').value,
                insName: document.getElementById('ins-select').options[document.getElementById('ins-select').selectedIndex].text,
                basicSalary: document.getElementById('basic-salary-input').value,
                basicComment: document.getElementById('basic-salary-comment').value,
                privateClassTotal: document.getElementById('commission-total').value,
                groupClassTotal: document.getElementById('group-class-commission-total').value || '0',
                salesTotal: document.getElementById('sales-commission-total').value || '0',
                salesRange: document.getElementById('current-rate-info').textContent.slice(6,) || '',
                otherRemarks: document.getElementById('other-remarks').value,
                otherAmount: document.getElementById('other-amount').value || '0',
                total: document.getElementById('total-cooperation-fee').textContent.match(/\d+\.\d+/)[0],
                privateClassDetails: [],
                groupClassDetails: [],
                salesDetails: []
            };

            // 收集私教课课提详情
            if (document.getElementById('private-class-section').style.display !== 'none') {
                document.querySelectorAll('#private-class-table tbody tr').forEach(row => {
                    const cells = row.querySelectorAll('td');
                            reportData.privateClassDetails.push({
                                cardId: cells[0].textContent,
                                clsType: cells[1].textContent,
                                clsName: cells[2].textContent,
                                cusName: cells[3].textContent,
                                clsCount: cells[6].textContent,  // 课时数
                                buyDate: cells[7].textContent,   // 购课日期
                                pay : cells[8].textContent,
                                real_pay: cells[9].textContent,
                                perClassPrice: cells[10].textContent,  // 单节课价格
                                commission: cells[11].textContent,
                                remark: cells[12].textContent  // 备注
                            });
                });
            }

            // 收集小团课课提详情
            if (document.getElementById('group-class-section').style.display !== 'none') {
                document.querySelectorAll('#group-class-report-table tbody tr').forEach(row => {
                    const cells = row.querySelectorAll('td');
                    // console.log('cells:',cells);
                    reportData.groupClassDetails.push({
                        member: cells[1].textContent,
                        clsType: cells[2].textContent,
                        clsName: cells[3].textContent,
                        clsTime: cells[4].textContent,
                        clsCount: cells[5].textContent,
                        commission: cells[6].textContent
                    });
                });
            }

                // 收集销售详情
                if (document.getElementById('sales-section').style.display !== 'none') {
                    document.querySelectorAll('#sales-report-table tbody tr').forEach(row => {
                        const cells = row.querySelectorAll('td');
                        reportData.salesDetails.push({
                            cusName: cells[0].textContent,
                            buyDate: cells[1].textContent,
                            cardId: cells[2].textContent,
                            payAmount: cells[3].textContent,
                            realPay: cells[4].textContent,
                            comment: cells[5].textContent,
                            commission: cells[6].textContent
                        });
                    });
                }

                // 收集未结算课程详情
                if (document.getElementById('unsettled-section').style.display !== 'none') {
                    reportData.unsettledDetails = [];
                    document.querySelectorAll('#unsettled-report-table tbody tr').forEach(row => {
                        const cells = row.querySelectorAll('td');
                        reportData.unsettledDetails.push({
                            card_id: cells[0].textContent,
                            cls_type: cells[1].textContent,
                            cls_name: cells[2].textContent,
                            cus_name: cells[3].textContent,
                            buy_date: cells[4].textContent,
                            start_date: cells[5].textContent === '未开卡' ? null : cells[5].textContent,
                            days_since_start: cells[6].textContent === '未开卡' ? null : cells[6].textContent
                        });
                    });
                }
            
            console.log('reportData:',reportData);
                // 发送到后端保存
            fetch('/save_salary_report', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(reportData)
            })
            .then(response => response.json())
            .then(data => {
                if(data.res === 'ok') {
                    alert('报告保存成功');
                } else {
                    alert('保存失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('保存失败，请检查网络连接');
            });
        });

        let insList;
        let insId;
        let params;
        let salaryParams = {};
        // let data_ins = []; // 存储教练详细信息

        const insInfo=hideInsSelectBlockAndGetInsInfo();
        insId=insInfo.sessionInsId;
        insName=insInfo.sessionInsName;
        insRole=insInfo.sessionInsRole;
        console.log('ins_id:',insId)        

        // 设置默认月份为当前月份并加载初始数据
        document.addEventListener('DOMContentLoaded', function() {
            // loginCheck();

            //增加返回上一页按钮
            addGoLastPageBtn();
            
            
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            document.getElementById('month-input').value = `${year}-${month}`;

            fetch('/get_all_ins_list', {
                method: 'GET',
            })
            .then(response => response.json())
            .then(data => {
                console.log('ins list:',data);
                insList=data['ins_list'];
                const insSelect = document.getElementById('ins-select');
                // insSelect.innerHTML = '<option value="">全部教练</option>';
                insList.forEach(ins => {
                    const option = document.createElement('option');
                    option.value = ins.slice(0,8);
                    option.textContent = ins.slice(8,);
                    insSelect.appendChild(option);
                });
                // 设置默认选中陆伟杰
                insSelect.value = 'LZINS001';
                // 添加教练选择变化事件
                insSelect.addEventListener('change', function() {
                    updateInsTypeDisplay();
                    filterByMonth();
                });
                // 教练列表加载完成后再获取数据
                filterByMonth();
                // 初始加载时也更新教练类型显示
                updateInsTypeDisplay();
            })
            .catch(error => console.error('Error:', error));      

            fetch('/get_salary_params', {
                method: 'GET',
            })
            .then(response => response.json())
            .then(data => {
                console.log('salary params:', data);
                salaryParams = data;
            })
            .catch(error => console.error('Error:', error));      
        });

        

        // 渲染表格
        function renderTable(data) {
            const tableBody = document.querySelector('#salary-table tbody');
            tableBody.innerHTML = '';

            data.forEach(item => {
                const row = document.createElement('tr');
                
                // 处理数组格式数据
                if (Array.isArray(item)) {
                    row.innerHTML = `
                        <td>${item[0]}</td>
                        <td>${item[1]}</td>
                        <td>${item[2]}</td>
                        <td>${item[3]}</td>
                        <td>${item[4]}</td>
                        <td>${item[5]}</td>
                        <td>${item[6]}</td>
                        <td>${item[7]}</td>
                        <td>${parseGMTDate(item[8])}</td>
                        <td>${item[9]}</td>
                        <td>${parseFloat(item[10]).toFixed(2)}</td>
                        <td>${parseFloat(item[11]).toFixed(2)}</td>
                        <td>${parseFloat(item[12]).toFixed(2)}</td>
                        <td>${parseGMTDate(item[13])}</td>
                        <td><input type="checkbox" class="settle-checkbox" ${item[1] === '常规课程' ? 'checked' : (item[14] === 'yes' ? '' : 'checked')} value="${item[0]}"></td>
                    `;
                } 
                // 处理对象格式数据
                else {
                    row.innerHTML = `
                        <td>${item.card_id}</td>
                        <td>${item.cls_type}</td>
                        <td>${item.cls_name}</td>
                        <td>${item.cus_id}</td>
                        <td>${item.cus_name}</td>
                        <td>${item.ins_id}</td>
                        <td>${item.ins_name}</td>
                        <td>${item.cls_tkn_qty}</td>
                        <td>${parseGMTDate(item.card_start_time)}</td>
                        <td>${item.days_from_start}</td>
                        <td>${parseFloat(item.pay).toFixed(2)}</td>
                        <td>${parseFloat(item.real_pay).toFixed(2)}</td>
                        <td>${parseFloat(item.avr_pay).toFixed(2)}</td>
                        <td>${parseGMTDate(item.buy_date)}</td>
                        <td>
                            ${calculateCommission(item)}
                        </td>
                        <td><input type="checkbox" class="settle-checkbox" ${item.cls_type === '常规课程' ? 'checked' : (item.cal_salary === 'yes' ? '' : 'checked')} value="${item.card_id}"></td>
                        <td></td>
                    `;
                }

                tableBody.appendChild(row);
            });

            // 添加checkbox事件监听
            document.querySelectorAll('.settle-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', calculateCommissionTotal);
            });

            // 显示课提汇总并计算初始总和
            document.getElementById('commission-summary').style.display = 'block';
            calculateCommissionTotal();
        }

        // 更新教练类型显示
        function updateInsTypeDisplay() {
            const insSelect = document.getElementById('ins-select');
            const insTypeDisplay = document.getElementById('ins-type-display');
            const basicSalaryInput = document.getElementById('basic-salary-input');
            const selectedInsId = insSelect.value;
            
            if (selectedInsId && window.data_ins && Array.isArray(window.data_ins) && window.data_ins.length > 0) {
                console.log('data_ins:', window.data_ins); // 调试日志
                const insData = window.data_ins[0]; // 直接取第一个元素
                if (insData.ins_id === selectedInsId) {
                    const isFullTime = insData.ins_type === 'full';
                    insTypeDisplay.textContent = isFullTime ? '全职教练' : '兼职教练';
                    basicSalaryInput.value = isFullTime ? (insData.basic_salary || '') : '0';
                    basicSalaryInput.readOnly = !isFullTime;
                    return;
                }
            }
            insTypeDisplay.textContent = '';
            basicSalaryInput.value = '';
        }

        // 根据选择的月份和教练筛选数据
        function filterByMonth() {
            const monthInput = document.getElementById('month-input').value;
            const insId = document.getElementById('ins-select').value;
            // 清空核算报告显示区
            document.getElementById('result-container').style.display = 'none';
            document.getElementById('basic-salary-section').style.display = 'none';
            document.getElementById('save-report-btn').style.display = 'none';
            document.getElementById('private-class-table').querySelector('tbody').innerHTML = '';
            document.getElementById('group-class-report-table').querySelector('tbody').innerHTML = '';
            document.getElementById('sales-report-table').querySelector('tbody').innerHTML = '';
            
            // 获取工资数据
            fetch('/get_ins_salary', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    month: monthInput,
                    ins_id: insId
                })
            })
            .then(response => response.json())
            .then(data => {
                if(data.res==='ok'){
                    console.log('ins salary data:', data)
                    // 存储教练详细信息
                    window.data_ins = data['data_ins'] ? [data['data_ins']] : [];
                    // 更新基本合作咨询费
                    if (data['data_ins'] && data['data_ins'].basic_salary) {
                        document.getElementById('basic-salary-input').value = data['data_ins'].basic_salary;
                    }
                    document.getElementById('salary-title').style.display = 'block';
                    renderTable(data['data']);
                    
                    // 渲染小团课清单
                    if(data['data_grp'] && data['data_grp'].length > 0) {
                        document.getElementById('group-class-title').style.display = 'block';
                        document.getElementById('group-class-table').style.display = 'table';
                        renderGroupClassTable(data['data_grp']);
                    } else {
                        document.getElementById('group-class-title').style.display = 'none';
                        document.getElementById('group-class-table').style.display = 'none';
                        document.getElementById('group-class-summary').style.display = 'none';
                    }

                    // 渲染销售清单
                    if(data['ins_sale_data'] && data['ins_sale_data'].length > 0) {
                        document.getElementById('sales-title').style.display = 'block';
                        document.getElementById('sales-table').style.display = 'table';
                        renderSalesTable(data['ins_sale_data']);
                    } else {
                        document.getElementById('sales-title').style.display = 'none';
                        document.getElementById('sales-table').style.display = 'none';
                    }
                    // 更新教练类型显示
                    updateInsTypeDisplay();
                    
                    // 渲染未结算私教课程清单
                    if(data['not_cal_salary_list'] && data['not_cal_salary_list'].length > 0) {
                        let hasUnsettledItems = false;
                        data['not_cal_salary_list'].forEach(item => {
                            //未结算私教课程清单不显示小团课清单
                            if(item.buy_cls_name!=='小团课'){
                                const checkbox = document.querySelector(`.settle-checkbox[value="${item.card_id}"]`);
                                if (!checkbox || !checkbox.checked) {
                                hasUnsettledItems = true;
                            }
                            }
                            
                        });
                        
                        if (hasUnsettledItems) {
                            document.getElementById('unsettled-title').innerHTML = '<h2>未结算私教课程清单</h2>';
                            document.getElementById('unsettled-title').style.display = 'block';
                            document.getElementById('unsettled-table').style.display = 'table';
                            renderUnsettledTable(data['not_cal_salary_list']);
                        } else {
                            document.getElementById('unsettled-title').innerHTML = '<h2>未结算私教课程清单</h2><div style="text-align: left; padding: 10px;">无</div>';
                            document.getElementById('unsettled-title').style.display = 'block';
                            document.getElementById('unsettled-table').style.display = 'none';
                        }
                    } else {
                        document.getElementById('unsettled-title').innerHTML = '<h2>未结算私教课程清单</h2><div style="text-align: left; padding: 10px;">无</div>';
                        document.getElementById('unsettled-title').style.display = 'block';
                        document.getElementById('unsettled-table').style.display = 'none';
                    }
                }else{
                    console.log('error',data.msg)
                    document.getElementById('salary-title').style.display = 'none';
                    document.getElementById('sales-title').style.display = 'none';
                    document.getElementById('sales-table').style.display = 'none';
                    document.getElementById('unsettled-title').style.display = 'none';
                    document.getElementById('unsettled-table').style.display = 'none';
                }
            })
            .catch(error => console.error('Error:', error));
        }

        // 解析GMT日期字符串为YYYY-MM-DD格式
        function parseGMTDate(gmtStr) {
            const date = new Date(gmtStr);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }

        // 格式化时间为YYYY-MM-DD HH:MM:SS
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 计算销售总金额
        function calculateSalesTotal() {
            const checkboxes = document.querySelectorAll('.sales-settle-checkbox');
            let total = 0;
            checkboxes.forEach(checkbox => {
                if(checkbox.checked) {
                    const row = checkbox.closest('tr');
                    const payAmount = parseFloat(row.querySelector('td:nth-child(6)').textContent);
                    total += payAmount;
                }
            });
            document.getElementById('sales-total').value = total.toFixed(2);
            calculateSalesCommission(total);
            
            // 更新表格行的显示样式
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                if(checkbox.checked) {
                    row.style.opacity = '1';
                    row.querySelector('td:nth-child(6)').style.fontWeight = 'bold';
                } else {
                    row.style.opacity = '0.6';
                    row.querySelector('td:nth-child(6)').style.fontWeight = 'normal';
                }
            });
        }

        function calculateSalesCommissionFromInput() {
            const inputValue = parseFloat(document.getElementById('sales-total').value) || 0;
            calculateSalesCommission(inputValue);
        }

        // 处理小团课课提结算金额input框修改
        function updateGroupClassCommissionFromInput() {
            const inputValue = parseFloat(document.getElementById('group-class-commission-total').value) || 0;
            // 这里可以添加其他逻辑，比如更新相关数据或重新计算
            console.log('小团课课提结算金额已更新为:', inputValue);
        }

function calculateSalesCommission(total) {
    // 根据销售总额计算提成
    const commissionRates = salaryParams['销提'] || {};
    let commission = 0;
    let rateInfo = '';
    
    // 如果总销售金额为0，则提成为0
    if (total === 0) {
        document.getElementById('current-rate-info').textContent = '销售金额为0，提成为0';
        document.getElementById('sales-commission-total').value = '0.00';
        return;
    }
    
    for (const [range, rate] of Object.entries(commissionRates)) {
        const [min, max] = range.match(/\d+/g).map(Number);
        if (total >= min && (isNaN(max) || total < max)) {
            commission = total * rate;
            rateInfo = `销售区间: ${range}:${Math.round(rate * 100)}%`;
            break;
        }
    }
    
    document.getElementById('current-rate-info').textContent = rateInfo;
    document.getElementById('sales-commission-total').value = commission.toFixed(2);
}

        function calculateCommission(item) {
            // 获取课程类型和名称
            const clsType = item.cls_type;
            const clsName = item.cls_name;
            
            // 从salaryParams获取对应比例
            let rate = 0;
            if (clsType === '限时课程') {
                rate = salaryParams['课提']['限时课程'][clsName] || 0;
                return (parseFloat(item.pay) * rate).toFixed(2);
            } else if (clsType === '常规课程') {
                rate = salaryParams['课提']['常规课程'][clsName] || 0;
                return (parseFloat(item.cls_tkn_qty) * parseFloat(item.avr_pay) * rate).toFixed(2);
            }
            return '0.00';
        }

        function calculateCommissionTotal() {
            const checkboxes = document.querySelectorAll('.settle-checkbox');
            let total = 0;
            checkboxes.forEach(checkbox => {
                if(checkbox.checked) {
                    const row = checkbox.closest('tr');
                    const commission = parseFloat(row.querySelector('td:nth-child(15)').textContent);
                    total += commission;
                }
            });
            document.getElementById('commission-total').value = total.toFixed(2);
            
            // 更新表格行的显示样式
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                if(checkbox.checked) {
                    row.style.opacity = '1';
                    row.querySelector('td:nth-child(15)').style.fontWeight = 'bold';
                } else {
                    row.style.opacity = '0.6';
                    row.querySelector('td:nth-child(15)').style.fontWeight = 'normal';
                }
            });

            // 检查是否有未结算课程需要显示
            const unsettledRows = document.querySelectorAll('#unsettled-table tbody tr');
            let hasUnsettledItems = false;
            unsettledRows.forEach(row => {
                if (row.style.display !== 'none') {
                    hasUnsettledItems = true;
                }
            });

            if (hasUnsettledItems) {
                document.getElementById('unsettled-title').innerHTML = '<h2>未结算私教课程清单</h2>';
                document.getElementById('unsettled-title').style.display = 'block';
                document.getElementById('unsettled-table').style.display = 'table';
            } else {
                document.getElementById('unsettled-title').innerHTML = '<h2>未结算私教课程清单</h2><div style="text-align: left; padding: 10px;">无</div>';
                document.getElementById('unsettled-title').style.display = 'block';
                document.getElementById('unsettled-table').style.display = 'none';
            }
            updateUnsettledRowNumbers();
        }

        // 渲染小团课表格
        function renderGroupClassTable(data) {
            const tableBody = document.querySelector('#group-class-table tbody');
            tableBody.innerHTML = '';

            data.forEach((item, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>${item.grp_cus_name}</td>
                    <td>${item.cls_type}</td>
                    <td>${item.cls_name}</td>
                    <td>${parseGMTDate(item.cls_datetime)}</td>
                    <td>${item.cls_tkn_qty}</td>
                    <td class="editable-group-commission">${(item.avr_pay_for_ins * item.cls_tkn_qty).toFixed(2)}</td>
                    <td><input type="checkbox" class="group-settle-checkbox" checked value="${index}"></td>
                `;
                tableBody.appendChild(row);

                // 为小团课"结算课提"单元格添加双击事件
                const commissionCell = row.querySelector('.editable-group-commission');
                commissionCell.addEventListener('dblclick', function() {
                    const originalValue = this.textContent;
                    const input = document.createElement('input');
                    input.type = 'number';
                    input.value = originalValue;
                    input.style.width = '80px';
                    input.style.textAlign = 'center';
                    
                    this.innerHTML = '';
                    this.appendChild(input);
                    input.focus();
                    
                    // 处理输入完成
                    const handleInputComplete = () => {
                        const newValue = parseFloat(input.value).toFixed(2);
                        this.textContent = newValue;
                        
                        // 重新计算小团课总课提
                        calculateGroupClassCommissionTotal();
                    };
                    
                    input.addEventListener('blur', handleInputComplete);
                    input.addEventListener('keypress', function(e) {
                        if (e.key === 'Enter') {
                            handleInputComplete();
                        }
                    });
                });
            });

            // 添加checkbox事件监听
            document.querySelectorAll('.group-settle-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', calculateGroupClassCommissionTotal);
            });

            // 显示课提汇总并计算初始总和
            document.getElementById('group-class-summary').style.display = 'block';
            calculateGroupClassCommissionTotal();
        }

        // 计算小团课课提总金额
        function calculateGroupClassCommissionTotal() {
            const checkboxes = document.querySelectorAll('.group-settle-checkbox');
            let total = 0;
            checkboxes.forEach(checkbox => {
                if(checkbox.checked) {
                    const row = checkbox.closest('tr');
                    const commission = parseFloat(row.querySelector('td:nth-child(7)').textContent);
                    total += commission;
                }
            });
            document.getElementById('group-class-commission-total').value = total.toFixed(2);
            
            // 更新表格行的显示样式
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                if(checkbox.checked) {
                    row.style.opacity = '1';
                    row.querySelector('td:nth-child(6)').style.fontWeight = 'bold';
                } else {
                    row.style.opacity = '0.6';
                    row.querySelector('td:nth-child(6)').style.fontWeight = 'normal';
                }
            });
        }

        // 渲染销售表格
        function renderSalesTable(data) {
            const tableBody = document.querySelector('#sales-table tbody');
            tableBody.innerHTML = '';

            data.forEach((item, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>${item.cus_name}</td>
                    <td>${parseGMTDate(item.buy_date)}</td>
                    <td>${item.card_id}</td>
                    <td>${item.cashier_name}</td>
                    <td>${parseFloat(item.pay).toFixed(2)}</td>
                    <td>${parseFloat(item.real_pay).toFixed(2)}</td>
                    <td>${item.comment || ''}</td>
                    <td><input type="checkbox" class="sales-settle-checkbox" checked value="${index}"></td>
                `;
                tableBody.appendChild(row);
            });

            // 添加checkbox事件监听
            document.querySelectorAll('.sales-settle-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', calculateSalesTotal);
            });

            // 显示销售汇总并计算初始总和
            document.getElementById('sales-summary').style.display = 'block';
            document.getElementById('sales-commission-summary').style.display = 'block';
            calculateSalesTotal();
        }

        // 更新未结算课程行号
        function updateUnsettledRowNumbers() {
            const visibleRows = document.querySelectorAll('#unsettled-table tbody tr:not([style*="display: none"])');
            visibleRows.forEach((row, index) => {
                row.cells[0].textContent = index + 1;
            });
        }

        // 检查未结算私教课程清单状态
        function checkUnsettledListStatus() {
            const unsettledRows = document.querySelectorAll('#unsettled-table tbody tr');
            let hasVisibleRows = false;
            
            unsettledRows.forEach(row => {
                if (row.style.display !== 'none') {
                    hasVisibleRows = true;
                }
            });

            if (!hasVisibleRows) {
                document.getElementById('unsettled-title').innerHTML = '<h2>未结算私教课程清单</h2><div style="text-align: left; padding: 10px;">无</div>';
                document.getElementById('unsettled-table').style.display = 'none';
            } else {
                document.getElementById('unsettled-title').innerHTML = '<h2>未结算私教课程清单</h2>';
                document.getElementById('unsettled-table').style.display = 'table';
            }
        }

        // 渲染未结算课程表格
        function renderUnsettledTable(data) {
            const tableBody = document.querySelector('#unsettled-table tbody');
            tableBody.innerHTML = '';

            data.forEach((item, index) => {
                //未结算课程表格不显示“小团课”
                if(item.buy_cls_name!=='小团课'){
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${index + 1}</td>
                        <td>${item.card_id}</td>
                        <td>${item.buy_type}</td>
                        <td>${item.buy_cls_name}</td>
                        <td>${item.cus_name}</td>
                        <td>${parseGMTDate(item.buy_date)}</td>
                        <td>${item.card_start_date === '未开卡' ? '未开卡' : parseGMTDate(item.card_start_date)}</td>
                        <td>${item.days_since_start}</td>
                    `;
                    
                    // 初始加载时检查结算状态
                    const checkbox = document.querySelector(`.settle-checkbox[value="${item.card_id}"]`);
                    if (checkbox) {
                        row.style.display = checkbox.checked ? 'none' : '';
                    }
                    
                    tableBody.appendChild(row);
                }
            });
            updateUnsettledRowNumbers();
        }

        // 确保私教课checkbox事件绑定
        function bindSettleCheckboxEvents() {
            document.querySelectorAll('.settle-checkbox').forEach(checkbox => {
                // 先移除旧的事件监听器
                checkbox.removeEventListener('change', calculateCommissionTotal);
                // 添加新的事件监听器
                checkbox.addEventListener('change', function() {
                    calculateCommissionTotal();
                    // 当结算复选框状态变化时，更新未结算课程列表
                    const cardId = checkbox.value;
                    const unsettledRows = document.querySelectorAll('#unsettled-table tbody tr');
                    unsettledRows.forEach(row => {
                        // 比较卡号（第2列）而不是序号（第1列）
                        if(row.cells[1].textContent === cardId) {
                            row.style.display = checkbox.checked ? 'none' : '';
                        }
                    });
                    // 更新行号
                    updateUnsettledRowNumbers();
                    // 检查未结算私教课程清单状态
                    checkUnsettledListStatus();
                });
            });
        }

        // 初始化时绑定事件
        document.addEventListener('DOMContentLoaded', function() {
            bindSettleCheckboxEvents();
            
        // 全选/全不选按钮事件（仅针对销售清单）
        document.getElementById('select-all-btn').addEventListener('click', function() {
            document.querySelectorAll('.sales-settle-checkbox').forEach(checkbox => {
                checkbox.checked = true;
            });
            calculateSalesTotal();
        });

        document.getElementById('deselect-all-btn').addEventListener('click', function() {
            document.querySelectorAll('.sales-settle-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            calculateSalesTotal();
        });

        // 绑定生成核算报告按钮事件
            document.getElementById('confirm-btn').addEventListener('click', function() {
                // 清除之前生成的"其他情况"部分
                const existingOtherSections = document.querySelectorAll('#sales-section > div');
                existingOtherSections.forEach(section => {
                    if (section.querySelector('h3') && section.querySelector('h3').textContent.includes('其他情况')) {
                        section.remove();
                    }
                });

                // 设置报告标题和基本合作费用
                const month = document.getElementById('month-input').value;
                const insName = document.getElementById('ins-select').options[document.getElementById('ins-select').selectedIndex].text;
                document.getElementById('report-title').textContent = `${insName}教练${month.substring(0, 4)}年${month.substring(5, 7)}月合作咨询费用结算`;
                const basicSalary = `${document.getElementById('basic-salary-input').value}  元`|| '0';
                const basicComment = document.getElementById('basic-salary-comment').value;
                document.getElementById('basic-salary-display').textContent = basicSalary;
                
                if(basicSalary === '0'){
                    document.getElementById('basic-salary-section').style.display='none';
                }else{
                    document.getElementById('basic-salary-section').style.display='block';
                    if(basicComment) {
                        document.getElementById('basic-salary-display').textContent += `（${basicComment}）`;
                    }
                }

                document.getElementById('basic-salary-section').style.display
                
                // 1. 私教课课提结算表
                const privateTableBody = document.querySelector('#private-class-table tbody');
                privateTableBody.innerHTML = '';
                document.querySelectorAll('#salary-table tbody tr').forEach(row => {
                    if (row.querySelector('.settle-checkbox').checked) {
                        const newRow = document.createElement('tr');
                        newRow.innerHTML = `
                            <td>${row.cells[0].textContent}</td>  <!-- 卡号 -->
                            <td>${row.cells[1].textContent}</td>  <!-- 课程类型 -->
                            <td>${row.cells[2].textContent}</td>  <!-- 课程名称 -->
                            <td>${row.cells[4].textContent}</td>  <!-- 会员姓名 -->
                            <td>${row.cells[8].textContent}</td>  <!-- 开卡日期 -->
                            <td>${row.cells[9].textContent}</td>  <!-- 开卡天数 -->
                            <td>${parseInt(row.cells[7].textContent) || 0}</td>  <!-- 课时数(确保为整数) -->
                            <td>${row.cells[13].textContent}</td>  <!-- 购课日期 -->
                            <td>${row.cells[10].textContent}</td>  <!--应付金额 -->
                            <td>${row.cells[11].textContent}</td>  <!-- 实付金额 -->
                            <td>${row.cells[12].textContent}</td>  <!-- 单节课价格 -->
                            <td>${row.cells[14].textContent}</td>  <!-- 课提金额 -->
                            <td>${row.cells[16].textContent}</td>  <!-- 备注 -->
                        `;
                        privateTableBody.appendChild(newRow);
                    }
                });
                document.getElementById('private-class-total').textContent = document.getElementById('commission-total').value;
                
                // 2. 小团课课提结算表
                if (document.getElementById('group-class-table').style.display !== 'none') {
                    document.getElementById('group-class-section').style.display = 'block';
                    const groupTableBody = document.querySelector('#group-class-report-table tbody');
                    groupTableBody.innerHTML = '';
                    document.querySelectorAll('#group-class-table tbody tr').forEach(row => {
                        if (row.querySelector('.group-settle-checkbox').checked) {
                            const newRow = document.createElement('tr');
                            newRow.innerHTML = `
                                <td>${row.cells[0].textContent}</td>
                                <td>${row.cells[1].textContent}</td>
                                <td>${row.cells[2].textContent}</td>
                                <td>${row.cells[3].textContent}</td>
                                <td>${row.cells[4].textContent}</td>
                                <td>${row.cells[5].textContent}</td>
                                <td>${row.cells[6].textContent}</td>
                            `;
                            groupTableBody.appendChild(newRow);
                        }
                    });
                    document.getElementById('group-class-report-total').textContent = document.getElementById('group-class-commission-total').value;
                }
                
                // 3. 销售提成结算表
                if (document.getElementById('sales-table').style.display !== 'none') {
                    document.getElementById('sales-section').style.display = 'block';
                    const salesTableBody = document.querySelector('#sales-report-table tbody');
                    salesTableBody.innerHTML = '';
                    document.querySelectorAll('#sales-table tbody tr').forEach(row => {
                        if (row.querySelector('.sales-settle-checkbox').checked) {
                            const newRow = document.createElement('tr');
                            newRow.innerHTML = `
                                <td>${row.cells[1].textContent}</td>
                                <td>${row.cells[2].textContent}</td>
                                <td>${row.cells[3].textContent}</td>
                                <td>${row.cells[5].textContent}</td>
                                <td>${row.cells[6].textContent}</td>
                                <td>${row.cells[7].textContent}</td>
                            <td>${document.getElementById('sales-commission-total').value === '0.00' ? '0.00' : (parseFloat(row.cells[5].textContent) * 0.1).toFixed(2)}</td>
                            `;
                            salesTableBody.appendChild(newRow);
                        }
                    });
                    document.getElementById('sales-report-total').textContent = document.getElementById('sales-total').value;
                    document.getElementById('sales-commission-report-total').textContent = document.getElementById('sales-commission-total').value;
                document.getElementById('commission-rate-info').textContent = document.getElementById('current-rate-info').textContent;
                    
                    // 添加其他情况说明和金额
                    const otherRemarks = document.getElementById('other-remarks').value;
                    const otherAmount = parseFloat(document.getElementById('other-amount').value) || 0;
                    
                    if(otherRemarks) {
                        const otherSection = document.createElement('div');
                        otherSection.style.marginTop = '15px';
                        otherSection.innerHTML = `
                            <h3>· 其他情况</h3>
                            <p>${otherRemarks.replace(/\n/g, '<br>')}</p>
                            <p>涉及金额: ${otherAmount.toFixed(2)} 元</p>
                        `;
                        document.getElementById('sales-section').appendChild(otherSection);
                    } else {
                        const otherSection = document.createElement('div');
                        otherSection.style.marginTop = '15px';
                        otherSection.innerHTML = `
                            <h3>· 其他情况</h3>
                            <p>涉及金额: ${otherAmount.toFixed(2)} 元</p>
                        `;
                        document.getElementById('sales-section').appendChild(otherSection);
                    }
                }
                
                // 计算总合作费
                const basicSalaryValue = parseFloat(document.getElementById('basic-salary-input').value) || 0;
                const privateTotal = parseFloat(document.getElementById('commission-total').value) || 0;
                const groupTotal = parseFloat(document.getElementById('group-class-commission-total').value) || 0;
                const salesTotal = parseFloat(document.getElementById('sales-commission-total').value) || 0;
                const otherAmount = parseFloat(document.getElementById('other-amount').value) || 0;
                const total = basicSalaryValue + privateTotal + groupTotal + salesTotal + otherAmount;
                
                document.getElementById('total-cooperation-fee').textContent = 
                    `${insName}教练${month.substring(0, 4)}年${month.substring(5, 7)}月总合作费：${total.toFixed(2)}元`;
                
                // 4. 未结算私教课程清单
                const unsettledSection = document.getElementById('unsettled-section');
                unsettledSection.innerHTML = `
                    <h3>· 未结算私教课程清单</h3>
                    <div style="text-align: left; padding: 10px;">无</div>
                `;
                unsettledSection.style.display = 'block';
                
                if (document.getElementById('unsettled-table').style.display !== 'none') {
                    const unsettledTableBody = document.createElement('tbody');
                    let hasUnsettledItems = false;
                    
                    document.querySelectorAll('#unsettled-table tbody tr').forEach(row => {
                        if (row.style.display !== 'none') {
                            hasUnsettledItems = true;
                        }
                    });
                    
                    if (hasUnsettledItems) {
                        const table = document.createElement('table');
                        table.id = 'unsettled-report-table';
                        table.innerHTML = `
                            <thead>
                                <tr>
                                    <th>卡号</th>
                                    <th>课程类型</th>
                                    <th>课程名称</th>
                                    <th>会员姓名</th>
                                    <th>购课日期</th>
                                    <th>开卡日期</th>
                                    <th>开卡天数</th>
                                </tr>
                            </thead>
                        `;
                        table.appendChild(unsettledTableBody);
                        
                        document.querySelectorAll('#unsettled-table tbody tr').forEach(row => {
                            if (row.style.display !== 'none') {
                                const newRow = document.createElement('tr');
                                newRow.innerHTML = `
                                    <td>${row.cells[1].textContent}</td>
                                    <td>${row.cells[2].textContent}</td>
                                    <td>${row.cells[3].textContent}</td>
                                    <td>${row.cells[4].textContent}</td>
                                    <td>${row.cells[5].textContent}</td>
                                    <td>${row.cells[6].textContent}</td>
                                    <td>${row.cells[7].textContent}</td>
                                `;
                                unsettledTableBody.appendChild(newRow);
                            }
                        });
                        
                        unsettledSection.innerHTML = `
                            <h3>· 未结算私教课程清单</h3>
                        `;
                        unsettledSection.appendChild(table);
                    }
                }
                
                // 显示结果报告和保存按钮
                document.getElementById('result-container').style.display = 'block';
                document.getElementById('save-report-btn').style.display = 'inline-block';
            });
        });
        
        // 每次渲染表格后也重新绑定事件
        function renderTable(data) {
            const tableBody = document.querySelector('#salary-table tbody');
            tableBody.innerHTML = '';

            data.forEach(item => {
                const row = document.createElement('tr');
                
                // 处理数组格式数据
                if (Array.isArray(item)) {
                    row.innerHTML = `
                        <td>${item[0]}</td>
                        <td>${item[1]}</td>
                        <td>${item[2]}</td>
                        <td>${item[3]}</td>
                        <td>${item[4]}</td>
                        <td>${item[5]}</td>
                        <td>${item[6]}</td>
                        <td>${item[7]}</td>
                        <td>${parseGMTDate(item[8])}</td>
                        <td>${item[9]}</td>
                        <td>${parseFloat(item[10]).toFixed(2)}</td>
                        <td>${parseFloat(item[11]).toFixed(2)}</td>
                        <td>${parseFloat(item[12]).toFixed(2)}</td>
                        <td>${parseGMTDate(item[13])}</td>
                        <td class="editable-commission">
                            ${calculateCommission(item)}
                        </td>
                        <td><input type="checkbox" class="settle-checkbox" ${item[1] === '常规课程' ? 'checked' : (item[14] === 'yes' ? '' : 'checked')} value="${item[0]}"></td>
                    `;
                } 
                // 处理对象格式数据
                else {
                    row.innerHTML = `
                        <td>${item.card_id}</td>
                        <td>${item.cls_type}</td>
                        <td>${item.cls_name}</td>
                        <td>${item.cus_id}</td>
                        <td>${item.cus_name}</td>
                        <td>${item.ins_id}</td>
                        <td>${item.ins_name}</td>
                        <td>${item.cls_tkn_qty}</td>
                        <td>${parseGMTDate(item.card_start_time)}</td>
                        <td>${item.days_from_start}</td>
                        <td>${parseFloat(item.pay).toFixed(2)}</td>
                        <td>${parseFloat(item.real_pay).toFixed(2)}</td>
                        <td>${parseFloat(item.avr_pay).toFixed(2)}</td>
                        <td>${parseGMTDate(item.buy_date)}</td>
                        <td class="editable-commission">
                            ${calculateCommission(item)}
                        </td>
                        <td><input type="checkbox" class="settle-checkbox" ${item.cls_type === '常规课程' ? 'checked' : (item.cal_salary === 'yes' ? '' : 'checked')} value="${item.card_id}"></td>
                        <td class="editable-remark"></td>
                    `;
                }

        // 为"课提金额"单元格添加双击事件
        document.querySelectorAll('.editable-commission').forEach(cell => {
            cell.addEventListener('dblclick', function() {
                const originalValue = this.textContent;
                const input = document.createElement('input');
                input.type = 'number';
                input.value = originalValue;
                input.style.width = '80px';
                input.style.textAlign = 'center';
                
                this.innerHTML = '';
                this.appendChild(input);
                input.focus();
                
                // 处理输入完成
                const handleInputComplete = () => {
                    let newValue;
                    if (input.value === '' || isNaN(input.value)) {
                        // 如果未输入或输入无效，计算应付金额*0.35
                        const payAmount = parseFloat(row.cells[10].textContent);
                        newValue = (payAmount * 0.35).toFixed(2);
                    } else {
                        newValue = parseFloat(input.value).toFixed(2);
                    }
                    this.textContent = newValue;
                    
                    // 重新计算总课提
                    calculateCommissionTotal();
                };
                
                input.addEventListener('blur', handleInputComplete);
                input.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        handleInputComplete();
                    }
                });
            });
        });

        // 为"备注"单元格添加双击事件
        document.querySelectorAll('#salary-table tbody tr').forEach(row => {
            const remarkCell = row.cells[row.cells.length - 1]; // 最后一列是备注
            remarkCell.addEventListener('dblclick', function() {
                const originalValue = this.textContent;
                const input = document.createElement('input');
                input.type = 'text';
                input.value = originalValue;
                input.style.width = '100%';
                
                this.innerHTML = '';
                this.appendChild(input);
                input.focus();
                
                // 处理输入完成
                const handleInputComplete = () => {
                    this.textContent = input.value;
                };
                
                input.addEventListener('blur', handleInputComplete);
                input.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        handleInputComplete();
                    }
                });
            });
        });

        // 为"应付金额"单元格添加双击事件
                const payCell = row.cells[10];
                payCell.addEventListener('dblclick', function() {
                    const originalValue = this.textContent;
                    const input = document.createElement('input');
                    input.type = 'number';
                    input.value = originalValue;
                    input.style.width = '80px';
                    input.style.textAlign = 'center';
                    
                    this.innerHTML = '';
                    this.appendChild(input);
                    input.focus();
                    
                    // 处理输入完成
                    const handleInputComplete = () => {
                        const newValue = parseFloat(input.value).toFixed(2);
                        this.textContent = newValue;
                        
                        // 更新对应的数据项
                        const rowData = data.find(item => {
                            if (Array.isArray(item)) {
                                return item[0] === row.cells[0].textContent;
                            } else {
                                return item.card_id === row.cells[0].textContent;
                            }
                        });
                        
                        if (rowData) {
                            if (Array.isArray(rowData)) {
                                rowData[10] = newValue;
                            } else {
                                rowData.pay = newValue;
                            }
                        }
                        
                        // 重新计算课提金额
                        const commissionCell = row.cells[14];
                        commissionCell.textContent = calculateCommission(rowData);
                        
                        // 重新计算总课提
                        calculateCommissionTotal();
                    };
                    
                    input.addEventListener('blur', handleInputComplete);
                    input.addEventListener('keypress', function(e) {
                        if (e.key === 'Enter') {
                            handleInputComplete();
                        }
                    });
                });

                // 为"每节课应付"单元格添加双击事件
                const avrPayCell = row.cells[12];
                avrPayCell.addEventListener('dblclick', function() {
                    const originalValue = this.textContent;
                    const input = document.createElement('input');
                    input.type = 'number';
                    input.value = originalValue;
                    input.style.width = '80px';
                    input.style.textAlign = 'center';
                    
                    this.innerHTML = '';
                    this.appendChild(input);
                    input.focus();
                    
                    // 处理输入完成
                    const handleInputComplete = () => {
                        const newValue = parseFloat(input.value).toFixed(2);
                        this.textContent = newValue;
                        
                        // 更新对应的数据项
                        const rowData = data.find(item => {
                            if (Array.isArray(item)) {
                                return item[0] === row.cells[0].textContent;
                            } else {
                                return item.card_id === row.cells[0].textContent;
                            }
                        });
                        
                        if (rowData) {
                            if (Array.isArray(rowData)) {
                                rowData[12] = newValue;
                            } else {
                                rowData.avr_pay = newValue;
                            }
                        }
                        
                        // 重新计算课提金额
                        const commissionCell = row.cells[14];
                        commissionCell.textContent = calculateCommission(rowData);
                        
                        // 重新计算总课提
                        calculateCommissionTotal();
                    };
                    
                    input.addEventListener('blur', handleInputComplete);
                    input.addEventListener('keypress', function(e) {
                        if (e.key === 'Enter') {
                            handleInputComplete();
                        }
                    });
                });

                tableBody.appendChild(row);

                // 为"课提金额"单元格添加双击事件
                const commissionCell = row.querySelector('.editable-commission');
                commissionCell.addEventListener('dblclick', function() {
                    const originalValue = this.textContent;
                    const input = document.createElement('input');
                    input.type = 'number';
                    input.value = originalValue;
                    input.style.width = '80px';
                    input.style.textAlign = 'center';
                    
                    this.innerHTML = '';
                    this.appendChild(input);
                    input.focus();
                    
                    // 处理输入完成
                    const handleInputComplete = () => {
                        const newValue = parseFloat(input.value).toFixed(2);
                        this.textContent = newValue;
                        
                        // 重新计算总课提
                        calculateCommissionTotal();
                    };
                    
                    input.addEventListener('blur', handleInputComplete);
                    input.addEventListener('keypress', function(e) {
                        if (e.key === 'Enter') {
                            handleInputComplete();
                        }
                    });
                });

                // 为"备注"单元格添加双击事件
                const remarkCell = row.querySelector('.editable-remark');
                remarkCell.addEventListener('dblclick', function() {
                    const originalValue = this.textContent;
                    const input = document.createElement('input');
                    input.type = 'text';
                    input.value = originalValue;
                    input.style.width = '100%';
                    
                    this.innerHTML = '';
                    this.appendChild(input);
                    input.focus();
                    
                    // 处理输入完成
                    const handleInputComplete = () => {
                        this.textContent = input.value;
                    };
                    
                    input.addEventListener('blur', handleInputComplete);
                    input.addEventListener('keypress', function(e) {
                        if (e.key === 'Enter') {
                            handleInputComplete();
                        }
                    });
                });
            });

            // 绑定checkbox事件并确保联动功能
            bindSettleCheckboxEvents();

            // 显示课提汇总并计算初始总和
            document.getElementById('commission-summary').style.display = 'block';
            calculateCommissionTotal();
            
            // 初始加载时也更新未结算课程显示状态
            document.querySelectorAll('.settle-checkbox').forEach(checkbox => {
                const cardId = checkbox.value;
                const unsettledRows = document.querySelectorAll('#unsettled-table tbody tr');
                unsettledRows.forEach(row => {
                    if(row.cells[1].textContent === cardId) {
                        row.style.display = checkbox.checked ? 'none' : '';
                    }
                });
            });
        }
    </script>
</body>
</html>
